package com.kacheong.pms.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.kacheong.pms.POJO.PageBean;
import com.kacheong.pms.Util.NumberUtil;
import com.kacheong.pms.Value.StaticValue;
import com.kacheong.pms.dao.ICarDao;
import com.kacheong.pms.dao.ICarPositionDao;
import com.kacheong.pms.dao.IVipRecordDao;
import com.kacheong.pms.domain.Car;
import com.kacheong.pms.domain.CarPosition;
import com.kacheong.pms.domain.VipRecord;
import com.kacheong.pms.service.IParkingService;
import easypr.core.CharsRecognise;
import easypr.core.PlateDetect;
import org.bytedeco.javacpp.opencv_core;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

import static org.bytedeco.javacpp.opencv_highgui.imread;


@RestController
@RequestMapping("/car")
public class ParkingController {

    @Autowired
    private ICarDao carDao;
    @Autowired
    private IVipRecordDao vipRecordDao;

    @Autowired
    private IParkingService parkingService;

    @Autowired
    private ICarPositionDao carPositionDao;

    @RequestMapping("/autoPlate")
    public JSONObject autoPlate(){
        JSONObject jsonObject = new JSONObject();
        String result = StaticValue.AutoPlate();
        jsonObject.put("msg",StaticValue.success);
        jsonObject.put("plate",result);
        return jsonObject;
    }

    @RequestMapping("/autoParking")
    public JSONObject autoParking(){
        JSONObject jsonObject = new JSONObject();
        String plate = "";
        Map results = parkingService.parkingCar(plate);
        jsonObject.put("plate",results.get("plate"));
        jsonObject.put("area",results.get("area"));
        jsonObject.put("position",results.get("position"));
        return jsonObject;
    }

    @RequestMapping(value = "/leavingCar",method = RequestMethod.POST)
    public JSONObject leavingCar(@RequestBody Map<String,Object> params){
        String plate= (String) params.get("plate");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("msg",null);
        if (plate!=null&&!plate.equals("")){
            parkingService.leavingCar(plate);
            jsonObject.put("msg",StaticValue.success);
        }
        return jsonObject;
    }

    @RequestMapping("/test")
    public JSONObject test(@RequestParam Integer month){
        JSONObject jsonObject = new JSONObject();
        NumberUtil numberUtil = new NumberUtil();
        jsonObject.put("msg",numberUtil.monthToDay(month));
        return jsonObject;
    }

    @RequestMapping("/registerVip")
    public JSONObject registerVip(@RequestBody Map<String,Object> params){
        JSONObject jsonObject = new JSONObject();
        String plate = (String) params.get("plate");
        Integer month = new Integer((String) params.get("month"));
        String results;
        if (plate!=null&&month!=0){
            NumberUtil numberUtil = new NumberUtil();
            results = parkingService.registerVip(plate,numberUtil.monthToDay(month),month);
            jsonObject.put("msg",results);
        }
        return jsonObject;
    }

    @RequestMapping(value = "/getCarOut",method = RequestMethod.POST)
    public JSONArray getCarOut(@RequestBody Map<String,Object> params){
        JSONArray jsonArray;
        Integer currentPage = (Integer) params.get("currentPage");
        String hql ="FROM CarPosition carPosition WHERE carPosition.outTime = null";
        PageBean pageBean= carPositionDao.doPage(hql,currentPage,10);
        jsonArray = getCarOut(pageBean);
        return jsonArray;
    }

    @RequestMapping(value = "/searchCar",method = RequestMethod.POST)
    public JSONArray searchCar(@RequestBody Map<String,Object> params){
        JSONArray jsonArray = new JSONArray();
        String content = (String) params.get("content");
        Integer currentPage = (Integer) params.get("currentPage");
        if (content!=null){
            String hql = "FROM CarPosition carPosition WHERE carPosition.outTime = null AND CONCAT(carPosition.car.plate,carPosition.position.name,carPosition.position.area.info) like '%"+content+"%'" ;
            PageBean pageBean = carPositionDao.doPage(hql,currentPage,10);
            jsonArray = getCarOut(pageBean);
        }
        return jsonArray;
    }

    @RequestMapping(value = "/getCarRec",method = RequestMethod.POST)
    public JSONArray getCarRec(@RequestBody Map<String,Object> params){
        Integer currentPage = (Integer) params.get("currentPage");
        String hql ="FROM CarPosition";
        PageBean pageBean= carPositionDao.doPage(hql,currentPage,10);
        return getCarRec(pageBean);
    }

    @RequestMapping(value = "/searchCarRec",method = RequestMethod.POST)
    public JSONArray searchCarRec(@RequestBody Map<String,Object> params){
        Integer currentPage = (Integer) params.get("currentPage");
        String content = (String) params.get("content");
        String hql = "FROM CarPosition carPosition WHERE CONCAT(carPosition.car.plate,carPosition.position.name,carPosition.position.area.info) like '%"+content+"%'";
        PageBean pageBean = carPositionDao.doPage(hql,currentPage,10);
        return getCarRec(pageBean);
    }

    @RequestMapping("/getVipRec")
    public JSONArray getVipRec(@RequestBody Map<String,Object> params){
        JSONArray jsonArray = new JSONArray();
        Integer currentPage = (Integer) params.get("currentPage");
        String hql = "FROM VipRecord";
        PageBean pageBean= vipRecordDao.doPage(hql,currentPage,10);
        List list = pageBean.getList();
        for (Object aList : list) {
            VipRecord vipRecord = (VipRecord) aList;
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("plate", vipRecord.getCar().getPlate());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            jsonObject.put("time", sdf.format(vipRecord.getCreateTime()));
            jsonObject.put("month", vipRecord.getMonth());
            jsonObject.put("cost", vipRecord.getCost());
            jsonArray.add(jsonObject);
        }
        return jsonArray;
    }

    @RequestMapping("/getVipCar")
    public JSONArray getVipCar(@RequestBody Map<String,Object> params){
        Integer currentPage = (Integer) params.get("currentPage");
        String hql = "FROM Car car WHERE car.day != 0";
        PageBean pageBean= carDao.doPage(hql,currentPage,10);
        return getVipCar(pageBean);
    }

    @RequestMapping("/searchVipCar")
    public JSONArray searchVipCar(@RequestBody Map<String,Object> params){
        JSONArray jsonArray =new JSONArray();
        String content = (String) params.get("content");
        Integer currentPage = (Integer) params.get("currentPage");
        if (content!=null){
            String hql = "FROM Car car WHERE car.day != 0 AND CONCAT(car.plate,car.day) like '%"+content+"%'" ;
            PageBean pageBean = carPositionDao.doPage(hql,currentPage,10);
            jsonArray = getVipCar(pageBean);
        }
        return jsonArray;
    }

    @RequestMapping(value = "/judgePlate")
    public JSONObject judgePlate(HttpServletRequest request){
        JSONObject jsonObject = new JSONObject();
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        String path = request.getSession().getServletContext().getRealPath("/plate");
        try {
            for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
                MultipartFile mf = entity.getValue();
                //获取该文件的文件名
                String oldFileName = mf.getOriginalFilename();
                String newFileName = UUID.randomUUID().toString().replaceAll("-", "") +
                        oldFileName.substring(oldFileName.lastIndexOf("."));
                File file = new File(path + "/" + newFileName);
                mf.transferTo(file);
                file.mkdir();
                jsonObject.put("fileName",newFileName);
                String tmp = path+"/"+newFileName;
                //修改保存图片的路径 适用OpenCV api
                String imgPath = tmp.replace("\\","/");
                opencv_core.Mat src = imread(imgPath);
                PlateDetect plateDetect = new PlateDetect();
                plateDetect.setPDLifemode(true);
                Vector<opencv_core.Mat> matVector = new Vector<>();
                int recognizeResult=plateDetect.plateDetect(src, matVector);
                if (0 == recognizeResult) {
                    CharsRecognise cr = new CharsRecognise();
                    for (opencv_core.Mat aMatVector : matVector) {
                        String result = cr.charsRecognise(aMatVector);
                        System.out.println("Chars Recognised: " + result);
                        jsonObject.put("msg",result);
                    }
                }else{
                    System.out.println(recognizeResult);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonObject;
    }

    @RequestMapping("/manParking")
    public JSONObject manParking(@RequestBody Map<String,Object> params){
        JSONObject jsonObject = new JSONObject();
        String plate = (String) params.get("plate");
        Integer areaId = (Integer) params.get("areaId");
        Integer positionId = (Integer) params.get("positionId");
        if (plate!=null&&areaId!=0&&positionId!=0){
            Map<String,Object> map = parkingService.manParking(plate,positionId,areaId);
            jsonObject.put("plate",map.get("plate"));
            jsonObject.put("area",map.get("area"));
            jsonObject.put("position",map.get("position"));
        }
        return jsonObject;
    }

    private JSONArray getCarOut(PageBean pageBean){
        JSONArray jsonArray = new JSONArray();
        List list = pageBean.getList();
        for(Object aList :list){
            CarPosition carPosition = (CarPosition) aList;
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("plate", carPosition.getCar().getPlate());
            jsonObject.put("area", carPosition.getPosition().getArea().getInfo());
            jsonObject.put("position", carPosition.getPosition().getName());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            jsonObject.put("inTime", sdf.format(carPosition.getInTime()));
            jsonObject.put("status", "未离开");
            jsonObject.put("total",pageBean.getAllRow());
            jsonArray.add(jsonObject);
        }
        return jsonArray;
    }

    private JSONArray getCarRec(PageBean pageBean){
        JSONArray jsonArray = new JSONArray();
        List list = pageBean.getList();
        for (Object aList : list) {
            CarPosition carPosition = (CarPosition) aList;
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("plate", carPosition.getCar().getPlate());
            jsonObject.put("area", carPosition.getPosition().getArea().getInfo());
            jsonObject.put("position", carPosition.getPosition().getName());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            jsonObject.put("inTime", sdf.format(carPosition.getInTime()));
            jsonObject.put("total",pageBean.getAllRow());
            if (carPosition.getOutTime() != null) {
                jsonObject.put("status", "已离开");
                jsonObject.put("cost", carPosition.getCost().toString());
                jsonObject.put("outTime", sdf.format(carPosition.getOutTime()));
            } else
                jsonObject.put("status", "未离开");
            jsonArray.add(jsonObject);
        }
        return jsonArray;
    }

    private JSONArray getVipCar(PageBean pageBean){
        JSONArray jsonArray = new JSONArray();
        List list = pageBean.getList();
        for (Object aList : list) {
            Car car = (Car) aList;
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("plate",car.getPlate());
            jsonObject.put("day",car.getDay());
            jsonObject.put("total",pageBean.getAllRow());
            jsonArray.add(jsonObject);
        }
        return jsonArray;
    }
}
